package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.TimeUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDingdingMonthAttend;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDingdingDayAttendMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDingdingMonthAttendMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDingdingDayAttendParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDingdingMonthAttendParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDingdingDayAttendResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDingdingMonthAttendResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyDingdingDayAttendService;
import  cn.stylefeng.guns.sys.modular.system.service.BtyDingdingMonthAttendService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 半天妖-钉钉-月度-考勤查询 服务实现类
 * </p>
 *
 * @author wjk
 * @since 2022-05-30
 */
@Service
public class BtyDingdingMonthAttendServiceImpl extends ServiceImpl<BtyDingdingMonthAttendMapper, BtyDingdingMonthAttend> implements BtyDingdingMonthAttendService {


    @Autowired
    private BtyDingdingDayAttendService btyDingdingDayAttendService;

    @Autowired
    private BtyDingdingDayAttendMapper btyDingdingDayAttendMapper;

    @Override
    public void add(BtyDingdingMonthAttendParam param){
        BtyDingdingMonthAttend entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyDingdingMonthAttendParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyDingdingMonthAttendParam param){
        BtyDingdingMonthAttend oldEntity = getOldEntity(param);
        BtyDingdingMonthAttend newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyDingdingMonthAttendResult findBySpec(BtyDingdingMonthAttendParam param){
        return null;
    }

    @Override
    public List<BtyDingdingMonthAttendResult> findListBySpec(BtyDingdingMonthAttendParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyDingdingMonthAttendParam param){

        Page pageContext = getPageContext();
        if (ToolUtil.isEmpty(param.getAttendYearMonth())){
            //获取当前月的上个月
            String lastMonth = DateUtil.getLastMonth();
            param.setAttendYearMonth(lastMonth);
        }else {
            String[] split = param.getAttendYearMonth().split("-");
            String month = split[0] + split[1];
            param.setAttendYearMonth(month);
        }

        //一级区域
        if (ToolUtil.isNotEmpty(param.getFirLevel())){
            param.setDeptId(param.getFirLevel());
        }
        //二级区域
        if (ToolUtil.isNotEmpty(param.getSecLevel())){
            param.setDeptId(param.getSecLevel());
        }
        //三级区域
        if (ToolUtil.isNotEmpty(param.getThirdLevel())){
            param.setDeptId(param.getThirdLevel());
        }
        //四级区域
        if (ToolUtil.isNotEmpty(param.getFourLevel())){
            param.setDeptId(param.getFourLevel());
        }

        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(BtyDingdingMonthAttendParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyDingdingMonthAttend getOldEntity(BtyDingdingMonthAttendParam param) {
        return this.getById(getKey(param));
    }

    private BtyDingdingMonthAttend getEntity(BtyDingdingMonthAttendParam param) {
        BtyDingdingMonthAttend entity = new BtyDingdingMonthAttend();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    /**
     * 开始同步东更道部门的员工的每天数据到月度数据
     * 月度数据
     * @author
     * @Date 2022-04-18
     *钉钉 写成定时任务；
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> addBtyDingdingMonthAttend(BtyDingdingMonthAttendParam param) {
        //查询获取月份，默认上个月
        String  lastMonth = param.getAttendYearMonth();
        if(ToolUtil.isEmpty(param.getAttendYearMonth())){
            // 若没有传参数，则默认上月月的数据
            lastMonth  = TimeUtil.getLastMonthStr();
        }
        BtyDingdingDayAttendParam btyDingdingDayAttendParam = new BtyDingdingDayAttendParam();
        btyDingdingDayAttendParam.setAttendYearMonth(lastMonth);
        //获取月度考勤信息,从日数据表中
        List<BtyDingdingMonthAttend> list = btyDingdingDayAttendService.mergeAttendYearMonth(btyDingdingDayAttendParam);
        //增加id
        for(BtyDingdingMonthAttend ddma:list){
            ddma.setId(UUIDUtils.getId());
        }
        //删除月度当月度的数据
        Integer delSize = this.baseMapper.deleteByYearMonth(lastMonth);
        //批量插入考勤信息
        simpleSqlInsertBatch(list);
        Map<String, String> mapResult = new HashMap<>();
        mapResult.put("size",String.valueOf(list.size()));
        return mapResult;
    }

    /**
     *  将数据批量保存
     * @param list
     * @return
     */
    public int simpleSqlInsertBatch(List<BtyDingdingMonthAttend> list) {
        if (list == null || list.size() < 1) {
            return 0;
        }
        // 如果提交的列表条数小于提交阀值
        List<BtyDingdingMonthAttend>[] splitLists = splitLists(list, 50);
        for (List<BtyDingdingMonthAttend> tempList : splitLists) {
            this.baseMapper.addList(tempList);
            //this.saveBatch(tempList);
        }
        return list.size();
    }

    /**
     * 对一个列表按照splitNum进行分割。
     *
     * @param lists
     * @param splitNum
     * @param <T>
     * @return
     */
    public static <T>List<BtyDingdingMonthAttend>[] splitLists(List<BtyDingdingMonthAttend> lists, int splitNum) {
        int listSize;
        if (lists == null || (listSize = lists.size()) < 1) {
            return new ArrayList[0];
        }
        int length = listSize % splitNum == 0 ? listSize / splitNum : listSize / splitNum + 1;
        // 这里面如果用ArrayList，会在50行报错。ArrayList list = new List();这样会报错。
        List<BtyDingdingMonthAttend>[] results = new List[length];
        int fromIndex, toIndex;
        for (int i = 0; i < length; i++) {
            fromIndex = i * splitNum;
            toIndex = (fromIndex + splitNum) > listSize ? listSize : (fromIndex + splitNum);
            results[i] = lists.subList(fromIndex, toIndex);
        }
        return results;
    }



    /**
     * 导出excel
     * @param param
     * @return
     */
    @Override
    public List<BtyDingdingMonthAttendResult> export(BtyDingdingMonthAttendParam param) {
        Page pageContext = getPageContext();
        if (ToolUtil.isEmpty(param.getAttendYearMonth())){
            //获取当前月的上个月
            String lastMonth = DateUtil.getLastMonth();
            param.setAttendYearMonth(lastMonth);
        }else {
            String[] split = param.getAttendYearMonth().split("-");
            String month = split[0] + split[1];
            param.setAttendYearMonth(month);
        }

        //一级区域
        if (ToolUtil.isNotEmpty(param.getFirLevel())){
            param.setDeptId(param.getFirLevel());
        }
        //二级区域
        if (ToolUtil.isNotEmpty(param.getSecLevel())){
            param.setDeptId(param.getSecLevel());
        }
        //三级区域
        if (ToolUtil.isNotEmpty(param.getThirdLevel())){
            param.setDeptId(param.getThirdLevel());
        }
        //四级区域
        if (ToolUtil.isNotEmpty(param.getFourLevel())){
            param.setDeptId(param.getFourLevel());
        }

        List<BtyDingdingMonthAttendResult> list = this.baseMapper.getList(param);

        return list;
    }

    /**
     * 漏打卡详情
     * @param param
     * @return
     */
    @Override
    public ResponseData detailList(BtyDingdingMonthAttendParam param) {
        Map<String, List> map = new HashMap<>();
        map.put("attendList", new ArrayList<>());
        map.put("lateNumList", new ArrayList<>());
        map.put("requestOutList", new ArrayList<>());
        map.put("askLeaveList", new ArrayList<>());
        map.put("attendUpdateNoteList", new ArrayList<>());

        //获取缺卡数据
        List<BtyDingdingDayAttendResult> attendList = btyDingdingDayAttendMapper.getAttendList(param);

        //获取迟到数据
       List<BtyDingdingDayAttendResult> lateNumList = btyDingdingDayAttendMapper.getLateNumList(param);

        //获取外出申请数据
        List<BtyDingdingDayAttendResult> requestOutList = btyDingdingDayAttendMapper.getRequestOutList(param);
        if (ToolUtil.isNotEmpty(requestOutList)){
            for (BtyDingdingDayAttendResult result : requestOutList) {
                //判断是否包含,
                if (result.getRequestNote().contains(",")){
                    String[] split = result.getRequestNote().split(",");
                    for (String item : split) {
                        if (item.contains("外出")){
                            result.setRequestNote(item);
                        }
                    }
                }
            }
        }


        //获取请假数据
        List<BtyDingdingDayAttendResult> askLeaveList = btyDingdingDayAttendMapper.getAskLeaveList(param);

        if (ToolUtil.isNotEmpty(askLeaveList)){
            for (BtyDingdingDayAttendResult result : askLeaveList) {
                //判断是否包含,
                if (result.getRequestNote().contains(",")){
                    String[] split = result.getRequestNote().split(",");
                    for (String item : split) {
                        if (item.contains("假")){
                            result.setRequestNote(item);
                        }
                    }
                }
            }
        }

        //获取修改考勤状态数据
        List<BtyDingdingDayAttendResult> attendUpdateNoteList = btyDingdingDayAttendMapper.getAttendUpdateNoteList(param);

        map.put("attendList", attendList);
        map.put("lateNumList", lateNumList);
        map.put("requestOutList", requestOutList);
        map.put("askLeaveList", askLeaveList);
        map.put("attendUpdateNoteList", attendUpdateNoteList);

        return ResponseData.success(map);
    }

    /**
     * 同步月度数据到liu1_qin
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> synchronousliuQin() {
        //  删除liu1_qin 中数据的
        //删除liu1_qin 数据
        Integer delSize = this.baseMapper.deleteLiuQin();
        //  同步上个月的数据

        // 若没有传参数，则默认上月月的数据
        String lastMonth  = TimeUtil.getLastMonthStr();
        Integer insertSize = this.baseMapper.insertLiuQin(lastMonth);

        Map<String, String> mapResult = new HashMap<>();
        mapResult.put("size",String.valueOf(insertSize));
        return mapResult;
    }

}
